<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\TokenEnum;
use app\model\MediaAccountModel;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class CacheAdvertiserTokenWork extends BaseWork
{
    protected object $service;

    protected function configure()
    {
        // 指令配置
        $this->setName('cache_adv_token_work');
        $this->setDescription('缓存账户和token的关系');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $output->writeln('=======缓存账户和token的关系开始' . date('Y-m-d H:i:s', time()) . '=======');
        $redis = Cache::store('redis')->handler();
        $accounts = $this->_getAccounts();
        $accounts[] = ['advertiser_id' => 0];
        $keyName = TokenEnum::TOKEN_ADV_REDIS_KEY;
        if (! empty($accounts)) {
            try {
                $key = '';
                $data = [];
                foreach ($accounts as $val) {
                    if ($key && $key != $val['advertiser_id']) {
                        sort($data);
                        $redis->set($keyName . $key, implode(',', $data));
                        $data = [];
                    }
                    $key = $val['advertiser_id'];
                    $data[] = $val['media_token_id'] ?? 0;
                }
            } catch (\Exception $e) {
                $output->writeln('=======缓存账户和token的关系失败' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
            }
        }
        $output->writeln('=======缓存账户和token的关系结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取账户.
     */
    private function _getAccounts()
    {
        return MediaAccountModel::order('account_id desc')->select()->toArray();
    }
}
